# 多阶段构建Dockerfile for Spring Boot后端

# 第一阶段：构建阶段
FROM swr.cn-north-4.myhuaweicloud.com/ddn-k8s/docker.io/maven:3.8.6-openjdk-8 AS builder

WORKDIR /app

# 配置Maven使用阿里云镜像源
RUN mkdir -p /root/.m2 && \
    echo '<settings><mirrors><mirror><id>aliyun</id><mirrorOf>central</mirrorOf><url>https://maven.aliyun.com/repository/central</url></mirror></mirrors></settings>' > /root/.m2/settings.xml

# 复制pom.xml
COPY pom.xml .

# 只下载编译需要的依赖
RUN mvn dependency:resolve -B -q

# 复制源代码并快速构建
COPY src ./src
RUN mvn clean package -DskipTests -B -q

# 第二阶段：运行阶段
FROM swr.cn-north-4.myhuaweicloud.com/ddn-k8s/docker.io/library/openjdk:8-alpine

# 安装必要工具
RUN apk add --no-cache curl tzdata

# 设置时区
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' > /etc/timezone

# 创建应用目录
WORKDIR /app

# 创建非root用户
RUN addgroup -g 1000 appuser && adduser -u 1000 -G appuser -s /bin/sh -D appuser

# 创建日志目录
RUN mkdir -p logs && chown -R appuser:appuser /app

# 从构建阶段复制JAR文件
COPY --from=builder /app/target/web3-management-*.jar app.jar

# 切换到非root用户
USER appuser

# 暴露端口
EXPOSE 8080

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
  CMD curl -f http://localhost:8080/actuator/health || exit 1

# 启动应用
ENTRYPOINT ["java", "-Djava.security.egd=file:/dev/./urandom", "-Dspring.profiles.active=docker", "-jar", "app.jar"]
